/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * NuGat-API named Chameleon developed by Simon De Baets to Verimag.
 *
 */


package chameleon.model.automata;

import chameleon.model.formula.Formula;
import chameleon.model.formula.parser.BooleanParser;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;

/**
 *
 * @author simon
 */
public class AutomataFactory {

    public AutomataFactory (){
        ;
    }

    public static Automata createAutomata(NodeList from, NodeList to, NodeList label,
            NodeList state, int dec){

        Automata automata = new Automata();
        //First create the nodes

        for (int i=0; i < state.getLength(); ++i){
            NamedNodeMap attributes = state.item(i).getAttributes();
            String nodeName = attributes.getNamedItem("sid").getNodeValue();
            Node node = new Node(nodeName);
            automata.addNode(node.clone());
        }

        //second create the edge and adding to corresponding nodes.
        for (int i=0; i<from.getLength(); ++i){
            String source = from.item(i).getFirstChild().getNodeValue();
            String target = to.item(i).getFirstChild().getNodeValue();
            String labelTrans = label.item(i+dec).getFirstChild().getNodeValue();
            Formula labelTransFormula = label2formula(labelTrans);
            Edge edge = new Edge (source, target, labelTransFormula);


            automata.getNode(source).addInputEdge(edge.clone());
            automata.getNode(target).addOutputEdge(edge.clone());

        }

        return automata;
    }

    private static Formula label2formula(String labelTrans) {
        try {
            String[] labels = labelTrans.split(" ");
            String formula = "";
            for (int i = 0; i < labels.length; ++i) {
                formula += labels[i];
                if (i + 1 < labels.length) {
                    formula += "&";
                }
            }
            BooleanParser parser = new BooleanParser(formula);
            return parser.createFormula();
        } catch (IOException ex) {
            Logger.getLogger(AutomataFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

}
